﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebHoiChoMuaBan.Models;
using System.Data.Linq;
using WebHoiChoMuaBan.Controllers.Global;

namespace WebHoiChoMuaBan.Controllers.Helpers
{
    public class NewsProductHelper : HelperBase
    {
        public struct NewsProductResult
        {
            public int id;
            public string title;
            public string intro;
            public Province province;
            public DateTime pubDate;
            public decimal? price;
            public string priceUnit;
            public int viewCount;
            public string needType;
            public NewsProductThumb thumbs;
            public Member member;
            public bool state;
            public int like;
            public int? hot;
        }

        public struct FetchProductResult
        {
            public List<NewsProduct> products;
            public int totalPages;
        }

        public const int NEED_SELL = 0;
        public const int NEED_BUY = 1;
        public const int NEED_RENT = 2;
        public const int NEED_NEW = 3;
        public const int NEED_ALL = 4;

        private int memberId;
        private MemberHelper memberHelper;
        public List<Member> gethotMember()
        {
            return (from e in base.dataContext.Members
                    where e.isHotMember == 1
                    select e).ToList<Member>();
        }
        public int MemberId
        {
            get { return memberId; }
            set { memberId = value; }
        }

        public NewsProductHelper()
        {
            this.memberId = 0;
            this.memberHelper = null;
        }

        public NewsProductHelper(int memberId)
            : base()
        {
            this.memberId = memberId;
            this.memberHelper = null;
        }

        public NewsProductHelper(MemberHelper hMem)
            : base()
        {
            this.memberHelper = hMem;
        }

        public List<NewsProduct> getProductAll()
        {
            return (from e in base.dataContext.NewsProducts
                    orderby e.NProDate descending
                    select e).Take<NewsProduct>(10).ToList<NewsProduct>();
        }

        public FetchProductResult AllNewsProductApprovedByMemId(int page, int rowPerPage, int? cateId)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (this.memberHelper == null)
            {
                if (this.memberId > 0) // Lấy tin tức mới do một thành viên nào đó đăng
                {
                    newNews = from m in this.dataContext.Members
                              join n in this.dataContext.NewsProducts
                              on m.MemId equals n.MemId
                              where m.MemId == this.memberId && n.NProState == true && n.CateId == cateId
                              orderby n.NProDate descending
                              select new NewsProductResult
                              {
                                  id = n.NProId,
                                  title = n.NProTitle,
                                  intro = n.NProIntro,
                                  province = n.Province,
                                  pubDate = n.NProDate,
                                  price = n.NProPrice,
                                  priceUnit = n.NProPriceUnit,
                                  viewCount = n.NProViewCount,
                                  state = n.NProState,
                                  member = n.Member,
                                  thumbs = (from t in n.NewsProductThumbs
                                            where t.NProThumbIsMain == true
                                            select t).First()
                              };
                }
            }
            return CreateListNews(page, rowPerPage, newNews);
        }

        public FetchProductResult AllNewsProductByCategory(int page, int rowPerPage, int cateId)
        {
            IEnumerable<NewsProductResult> newNews = null;
            newNews = from n in this.dataContext.NewsProducts
                      where n.CateId == cateId
                      orderby n.NProDate descending
                      select new NewsProductResult
                      {
                          id = n.NProId,
                          title = n.NProTitle,
                          intro = n.NProIntro,
                          province = n.Province,
                          pubDate = n.NProDate,
                          price = n.NProPrice,
                          priceUnit = n.NProPriceUnit,
                          viewCount = n.NProViewCount,
                          member = n.Member,
                          state = n.NProState,
                          thumbs = (from t in n.NewsProductThumbs
                                    where t.NProThumbIsMain == true
                                    select t).First()
                      };
            return CreateListNews(page, rowPerPage, newNews);
        }

        public FetchProductResult AllProductByMemId(int page, int rowPerPage)
        {
            IEnumerable<NewsProductResult> newNews = null;
            newNews = from n in this.dataContext.NewsProducts
                      where (n.MemId == memberId && n.isNews != 1)
                      orderby n.NProDate descending
                      select new NewsProductResult
                      {
                          id = n.NProId,
                          title = n.NProTitle,
                          intro = n.NProIntro,
                          province = n.Province,
                          pubDate = n.NProDate,
                          price = n.NProPrice,
                          priceUnit = n.NProPriceUnit,
                          viewCount = n.NProViewCount,
                          member = n.Member,
                          state = n.NProState,
                          like = n.NProLike,

                          thumbs = (from t in n.NewsProductThumbs
                                    where t.NProThumbIsMain == true
                                    select t).First()
                      };
            return CreateListNews(page, rowPerPage, newNews);
        }


        public FetchProductResult AllNewProductByMemId(int page, int rowPerPage)
        {
            IEnumerable<NewsProductResult> newNews = null;
            newNews = from n in this.dataContext.NewsProducts
                      where (n.MemId == memberId)
                      orderby n.NProDate descending
                      select new NewsProductResult
                      {
                          id = n.NProId,
                          title = n.NProTitle,
                          intro = n.NProIntro,
                          province = n.Province,
                          pubDate = n.NProDate,
                          price = n.NProPrice,
                          priceUnit = n.NProPriceUnit,
                          viewCount = n.NProViewCount,
                          member = n.Member,
                          state = n.NProState,
                          like = n.NProLike,

                          thumbs = (from t in n.NewsProductThumbs
                                    where t.NProThumbIsMain == true
                                    select t).First()
                      };
            return CreateListNews(page, rowPerPage, newNews);
        }

            public List<NewsProduct> AllRealEstateApprovedByMemId(int? uid)
        {
            return (from n in this.dataContext.NewsProducts
                    where n.NProState == true && n.MemId == uid.Value && n.RAttrId != null
                    select n).ToList();
        }

        //public List<NewsProduct> AllNewsProduct()
        //{
        //    return (from n in this.dataContext.NewsProducts
        //            orderby n.NProDate descending
        //            select n).ToList();
        //}

        public NewsProduct getNewsProductById(int id)
        {
            return this.dataContext.NewsProducts.SingleOrDefault(n => n.NProId == id);
        }

        public NewsProductComment getNewsProductCommentById(int id)
        {
            return this.dataContext.NewsProductComments.SingleOrDefault(n => n.NProId == id);
        }

        public FetchProductResult getListProduct(int pageNum)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (this.memberId > 0) // Lấy tin tức mới do một thành viên nào đó đăng
            {
                newNews = from m in this.dataContext.Members
                          join n in this.dataContext.NewsProducts
                          on m.MemId equals n.MemId
                          where m.MemId == this.memberId
                          //newNews = from n in this.dataContext.NewsProducts
                          //          where n.MemId == this.memberId
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              state = n.NProState,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            return CreateListNews(pageNum, Config.ITEMS_PER_PAGE, newNews);
        }

        //
        // Insert/Delete Methods
        public void Add(NewsProduct newsProduct)
        {
            this.dataContext.NewsProducts.InsertOnSubmit(newsProduct);
        }

        //Delete Methods
        public void Delete(NewsProduct product)
        {
            this.dataContext.NewsProducts.DeleteOnSubmit(product);
        }

        //
        // Persistence
        public void Save()
        {
            this.dataContext.SubmitChanges();
        }

        public NewsProduct getNews(int newsId)
        {
            try
            {
                var news = (from n in this.dataContext.NewsProducts
                            where n.NProId == newsId
                            select n).First();
                return news;
            }
            catch
            {
                return null;
            }
        }

        public FetchProductResult getNewNews(int needType, int provId, int cateId, int pageId, int pageNum, int rowPerPage)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (cateId > 0)
            {
                CategoryHelper hCate = new CategoryHelper();
                Category cate = hCate.getCate(cateId);
                newNews = from n in this.dataContext.NewsProducts
                          where n.CateId == cateId || n.Category.ParentCateId == cateId
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              needType = n.NProNeedType,
                              viewCount = n.NProViewCount,
                              state = n.NProState,
                              member = n.Member,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            else
            {
                newNews = from n in this.dataContext.NewsProducts
                          where (n.Category.PageId == pageId) || (n.Category.ParentCategory.PageId == pageId)
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
                //var news = newNews.ToList();
            }

            switch (needType)
            {
                case NEED_BUY: // Nếu là Mua
                    newNews = from n in newNews
                              where n.needType.ToLower().Contains("bu")
                              select n;
                    break;
                case NEED_RENT: // Nếu là Cho Thuê
                    newNews = from n in newNews
                              where n.needType.ToLower().Contains("re")
                              select n;
                    break;
                case NEED_NEW: // Nếu là Dự Án Mới
                    newNews = from n in newNews
                              where n.needType.ToLower().Contains("ne")
                              select n;
                    break;
                case NEED_SELL: // Nếu là Bán (NEED_SELL)
                default:
                    newNews = from n in newNews
                              where n.needType.ToLower().Contains("se")
                              select n;
                    break;
            }

            if (provId > 1) // Không phải "Toàn quốc"
                newNews = from n in newNews
                          where n.province.ProvId == provId
                          select n;

            return CreateListNews(pageNum, rowPerPage, newNews);
        }

        public FetchProductResult getNewNews(int pageNum, int rowPerPage)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (this.memberHelper == null)
            {
                if (this.memberId > 0) // Lấy tin tức mới do một thành viên nào đó đăng
                {
                    newNews = from m in this.dataContext.Members
                              join n in this.dataContext.NewsProducts
                              on m.MemId equals n.MemId
                              where m.MemId == this.memberId && n.isNews == 0
                              orderby n.NProDate descending
                              select new NewsProductResult
                              {
                                  id = n.NProId,
                                  title = n.NProTitle,
                                  intro = n.NProIntro,
                                  province = n.Province,
                                  pubDate = n.NProDate,
                                  price = n.NProPrice,
                                  priceUnit = n.NProPriceUnit,
                                  viewCount = n.NProViewCount,
                                  needType = n.NProNeedType,
                                  member = n.Member,
                                  state = n.NProState,
                                  thumbs = (from t in n.NewsProductThumbs
                                            where t.NProThumbIsMain == true
                                            select t).First()
                              };
                }
                else //Lấy tin tức mới nhất của mọi người
                {
                    newNews = from n in this.dataContext.NewsProducts
                              where n.isNews == 0
                              orderby n.NProDate descending
                              select new NewsProductResult
                              {
                                  id = n.NProId,
                                  title = n.NProTitle,
                                  intro = n.NProIntro,
                                  province = n.Province,
                                  pubDate = n.NProDate,
                                  price = n.NProPrice,
                                  priceUnit = n.NProPriceUnit,
                                  viewCount = n.NProViewCount,
                                  needType = n.NProNeedType,
                                  member = n.Member,
                                  state = n.NProState,
                                  thumbs = (from t in n.NewsProductThumbs
                                            where t.NProThumbIsMain == true
                                            select t).First()
                              };
                }
            }
            else //Lấy tin tức từ một đối tượng đã load sẵn
            {
                newNews = from n in this.memberHelper.Member.NewsProducts
                          where n.isNews == 0
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }

            return CreateListNews(pageNum, rowPerPage, newNews);
        }

        public FetchProductResult getNewNews(int page, int rowPerPage, int cateId)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (this.memberHelper == null)
            {
                if (this.memberId > 0) // Lấy tin tức mới do một thành viên nào đó đăng
                {
                    newNews = from m in this.dataContext.Members
                              join n in this.dataContext.NewsProducts
                              on m.MemId equals n.MemId
                              where m.MemId == this.memberId && n.CateId == cateId && n.isNews == 0
                              orderby n.NProDate descending
                              select new NewsProductResult
                              {
                                  id = n.NProId,
                                  title = n.NProTitle,
                                  intro = n.NProIntro,
                                  province = n.Province,
                                  pubDate = n.NProDate,
                                  price = n.NProPrice,
                                  priceUnit = n.NProPriceUnit,
                                  viewCount = n.NProViewCount,
                                  needType = n.NProNeedType,
                                  state = n.NProState,
                                  member = n.Member,
                                  thumbs = (from t in n.NewsProductThumbs
                                            where t.NProThumbIsMain == true
                                            select t).First()
                              };
                }
                else //Lấy tin tức mới nhất của mọi người
                {
                    newNews = from n in this.dataContext.NewsProducts
                              where n.CateId == cateId && n.isNews == 0
                              orderby n.NProDate descending
                              select new NewsProductResult
                              {
                                  id = n.NProId,
                                  title = n.NProTitle,
                                  intro = n.NProIntro,
                                  province = n.Province,
                                  pubDate = n.NProDate,
                                  price = n.NProPrice,
                                  priceUnit = n.NProPriceUnit,
                                  viewCount = n.NProViewCount,
                                  needType = n.NProNeedType,
                                  member = n.Member,
                                  state = n.NProState,
                                  thumbs = (from t in n.NewsProductThumbs
                                            where t.NProThumbIsMain == true
                                            select t).First()
                              };
                }
            }
            else //Lấy tin tức từ một đối tượng đã load sẵn
            {
                newNews = from n in this.memberHelper.Member.NewsProducts
                          where n.CateId == cateId && n.isNews == 0
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }

            return CreateListNews(page, rowPerPage, newNews);
        }

        public FetchProductResult getHotNews(int? pageId, int? cateid, int page, int rowPerPage)
        {
            IEnumerable<NewsProductResult> hotNews = null;

            if (pageId != null && cateid != 0)
            {
                List<Category> lstChild = new CategoryHelper().GetChildCategoryById(cateid.Value);
                List<int> lstInt = new List<int>();
                if (lstChild.Count == 0)
                {
                    lstInt.Add(cateid.Value);
                }
                else
                {
                    foreach (Category cat in lstChild)
                    {
                        lstInt.Add(cat.CateId);
                    }
                }
                hotNews = from n in base.dataContext.NewsProducts
                          where lstInt.Contains(n.CateId) && (n.isHotNewsProduct == 1)
                          orderby n.NProUpTime descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              hot = n.isHotNewsProduct,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First<NewsProductThumb>()
                          };
            }
            else if (pageId != null && cateid == 0)
            {
                List<Category> lstCates = new CategoryHelper().getCates(pageId);
                List<Category> lstchild = new CategoryHelper().getChildFromParrent(lstCates);
                List<int> lstInt = new List<int>();
                foreach (Category cat in lstchild)
                {
                    lstInt.Add(cat.CateId);
                }
                hotNews = from n in base.dataContext.NewsProducts
                          where lstInt.Contains(n.CateId) && (n.isHotNewsProduct == 1)
                          orderby n.NProUpTime descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First<NewsProductThumb>()
                          };
            }
            else if (pageId == null && cateid == null)
            {
                hotNews = from n in base.dataContext.NewsProducts
                          where (n.isHotNewsProduct == 1) && (n.isNews == 0)
                          orderby n.NProUpTime descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              needType = n.NProNeedType,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First<NewsProductThumb>()
                          };
            }
            if (hotNews.Count<NewsProductResult>() > 0)
            {
                return this.CreateListNews(page, hotNews.Count<NewsProductResult>(), hotNews);
            }
            return this.CreateListNews(page, 1, hotNews);
        }

        public FetchProductResult GetHotOrderNews(int? pageId, int? cId, int page, int rowPerPage)
        {
            IEnumerable<NewsProductResult> newNewss;
            DateTime refeshTime;
            DateTime currentTime;
            List<NewsProductResult> newNews;
            List<NewsProductResult> newOrderNews;
            int i;
            IEnumerable<NewsProductResult> resultNews;
            int? cateid = cId;
            if (pageId != null && cateid != 0)
            {
                List<HotNewsProductDetail> hotNews;
                List<Category> lstParr;
                Category cat = new CategoryHelper().GetCategoryById(cId.Value);
                if (cat.CateCount > 0)
                {
                    lstParr = new CategoryHelper().GetChildCategoryById(cId.Value);
                    List<int> lstcInt = new List<int>();
                    foreach (Category cat1 in lstParr)
                    {
                        lstcInt.Add(cat1.CateId);
                    }
                    hotNews = (from e in base.dataContext.HotNewsProductDetails
                               where lstcInt.Contains((int)e.NproCatId)
                               orderby e.NProOrder descending
                               select e).ToList<HotNewsProductDetail>();
                }
                else
                {
                    hotNews = (from e in base.dataContext.HotNewsProductDetails
                               where e.NproCatId == cId
                               orderby e.NProOrder descending
                               select e).ToList<HotNewsProductDetail>();
                }
                if (hotNews.Count == 0)
                {
                    newNewss = from n in base.dataContext.NewsProducts
                               where false
                               select new NewsProductResult
                               {
                                   id = n.NProId,
                                   title = n.NProTitle,
                                   intro = n.NProIntro,
                                   province = n.Province,
                                   pubDate = n.NProDate,
                                   price = n.NProPrice,
                                   priceUnit = n.NProPriceUnit,
                                   viewCount = n.NProViewCount,
                                   needType = n.NProNeedType,
                                   state = n.NProState,
                                   member = n.Member,
                                   thumbs = (from t in n.NewsProductThumbs
                                             where t.NProThumbIsMain == true
                                             select t).First<NewsProductThumb>()
                               };
                    return this.CreateListNews(page, rowPerPage, newNewss);
                }
                foreach (HotNewsProductDetail hot in hotNews)
                {
                    if (hot.NProLoopCount == 0)
                    {
                        base.dataContext.HotNewsProductDetails.DeleteOnSubmit(hot);
                    }
                    else
                    {
                        refeshTime = hot.NProNextRefesh;
                        currentTime = DateTime.Now;
                        if (this.checkTwoDate(refeshTime, currentTime))
                        {
                            hot.NProOrder = 1;
                            foreach (HotNewsProductDetail h in hotNews)
                            {
                                if (h.NProId != hot.NProId)
                                {
                                    h.NProOrder++;
                                }
                            }
                            hot.NProNextRefesh = hot.NProNextRefesh.AddHours((double)hot.NProInterval);
                        }
                    }
                }
                base.dataContext.SubmitChanges();
                if (cat.CateCount > 0)
                {
                    lstParr = new CategoryHelper().GetChildCategoryById(cId.Value);
                    List<int> lstcInt = new List<int>();
                    foreach (Category cat1 in lstParr)
                    {
                        lstcInt.Add(cat1.CateId);
                    }
                    hotNews = (from e in base.dataContext.HotNewsProductDetails
                               where lstcInt.Contains((int)e.NproCatId)
                               orderby e.NProOrder descending
                               select e).ToList<HotNewsProductDetail>();
                }
                else
                {
                    hotNews = (from e in base.dataContext.HotNewsProductDetails
                               where e.NproCatId == cId
                               orderby e.NProOrder descending
                               select e).ToList<HotNewsProductDetail>();
                }
                List<int> lstIDHotNews = new List<int>();
                foreach (HotNewsProductDetail hot in hotNews)
                {
                    lstIDHotNews.Add(hot.NProId);
                }
                newNews = (from n in base.dataContext.NewsProducts
                           where lstIDHotNews.Contains(n.NProId)
                           select new NewsProductResult
                           {
                               id = n.NProId,
                               title = n.NProTitle,
                               intro = n.NProIntro,
                               province = n.Province,
                               pubDate = n.NProDate,
                               price = n.NProPrice,
                               priceUnit = n.NProPriceUnit,
                               viewCount = n.NProViewCount,
                               needType = n.NProNeedType,
                               state = n.NProState,
                               member = n.Member,
                               thumbs = (from t in n.NewsProductThumbs
                                         where t.NProThumbIsMain == true
                                         select t).First<NewsProductThumb>()
                           }).ToList<NewsProductResult>();
                newOrderNews = new List<NewsProductResult>(newNews.Count);
                for (i = 0; i < lstIDHotNews.Count; i++)
                {
                    foreach (NewsProductResult news in newNews)
                    {
                        if (news.id == lstIDHotNews[i])
                        {
                            newOrderNews.Add(news);
                            break;
                        }
                    }
                }
                resultNews = newOrderNews;
                return this.CreateListNews(page, rowPerPage, resultNews);
            }

            if (pageId != null && cateid == 0)
            {
                List<HotNewsProductPage> hotNews = (from e in base.dataContext.HotNewsProductPages
                                                    orderby e.NProOrder descending
                                                    select e).ToList<HotNewsProductPage>();
                if (hotNews.Count == 0)
                {
                    newNewss = from n in base.dataContext.NewsProducts
                               where false
                               select new NewsProductResult
                               {
                                   id = n.NProId,
                                   title = n.NProTitle,
                                   intro = n.NProIntro,
                                   province = n.Province,
                                   pubDate = n.NProDate,
                                   price = n.NProPrice,
                                   priceUnit = n.NProPriceUnit,
                                   viewCount = n.NProViewCount,
                                   needType = n.NProNeedType,
                                   state = n.NProState,
                                   member = n.Member,
                                   thumbs = (from t in n.NewsProductThumbs
                                             where t.NProThumbIsMain == true
                                             select t).First<NewsProductThumb>()
                               };
                    return this.CreateListNews(page, rowPerPage, newNewss);
                }
                foreach (HotNewsProductPage hot in hotNews)
                {
                    if (hot.NProLoopCount == 0)
                    {
                        base.dataContext.HotNewsProductPages.DeleteOnSubmit(hot);
                    }
                    else
                    {
                        refeshTime = hot.NProNextRefesh;
                        currentTime = DateTime.Now;
                        if (this.checkTwoDate(refeshTime, currentTime))
                        {
                            hot.NProOrder = 1;
                            foreach (HotNewsProductPage h in hotNews)
                            {
                                if (h.NProId != hot.NProId)
                                {
                                    h.NProOrder++;
                                }
                            }
                            hot.NProNextRefesh = hot.NProNextRefesh.AddHours((double)hot.NProInterval);
                        }
                    }
                }
                base.dataContext.SubmitChanges();
                hotNews = (from e in base.dataContext.HotNewsProductPages
                           orderby e.NProOrder
                           select e).ToList<HotNewsProductPage>();
                List<int> lstIDHotNews = new List<int>();
                foreach (HotNewsProductPage hot in hotNews)
                {
                    lstIDHotNews.Add(hot.NProId);
                }
                newNews = (from n in base.dataContext.NewsProducts
                           where lstIDHotNews.Contains(n.NProId)
                           select new NewsProductResult
                           {
                               id = n.NProId,
                               title = n.NProTitle,
                               intro = n.NProIntro,
                               province = n.Province,
                               pubDate = n.NProDate,
                               price = n.NProPrice,
                               priceUnit = n.NProPriceUnit,
                               viewCount = n.NProViewCount,
                               needType = n.NProNeedType,
                               state = n.NProState,
                               member = n.Member,
                               thumbs = (from t in n.NewsProductThumbs
                                         where t.NProThumbIsMain == true
                                         select t).First<NewsProductThumb>()
                           }).ToList<NewsProductResult>();
                newOrderNews = new List<NewsProductResult>(newNews.Count);
                for (i = 0; i < lstIDHotNews.Count; i++)
                {
                    foreach (NewsProductResult news in newNews)
                    {
                        if (news.id == lstIDHotNews[i])
                        {
                            newOrderNews.Add(news);
                            break;
                        }
                    }
                }
                resultNews = newOrderNews;
                return this.CreateListNews(page, rowPerPage, resultNews);
            }
            if (pageId == null && cateid == null)
            {
                List<HotNewsProduct> hotNews = (from e in base.dataContext.HotNewsProducts
                                                orderby e.NProOrder descending
                                                select e).ToList<HotNewsProduct>();
                if (hotNews.Count == 0)
                {
                    newNewss = from n in base.dataContext.NewsProducts
                               where false
                               select new NewsProductResult
                               {
                                   id = n.NProId,
                                   title = n.NProTitle,
                                   intro = n.NProIntro,
                                   province = n.Province,
                                   pubDate = n.NProDate,
                                   price = n.NProPrice,
                                   priceUnit = n.NProPriceUnit,
                                   viewCount = n.NProViewCount,
                                   needType = n.NProNeedType,
                                   state = n.NProState,
                                   member = n.Member,
                                   thumbs = (from t in n.NewsProductThumbs
                                             where t.NProThumbIsMain == true
                                             select t).First<NewsProductThumb>()
                               };
                    return this.CreateListNews(page, rowPerPage, newNewss);
                }
                foreach (HotNewsProduct hot in hotNews)
                {
                    if (hot.NProLoopCount == 0)
                    {
                        base.dataContext.HotNewsProducts.DeleteOnSubmit(hot);
                    }
                    else
                    {
                        refeshTime = hot.NProNextRefesh;
                        currentTime = DateTime.Now;
                        if (this.checkTwoDate(refeshTime, currentTime))
                        {
                            hot.NProOrder = 1;
                            foreach (HotNewsProduct h in hotNews)
                            {
                                if (h.NProId != hot.NProId)
                                {
                                    h.NProOrder++;
                                }
                            }
                            hot.NProNextRefesh = hot.NProNextRefesh.AddHours((double)hot.NProInterval);
                        }
                    }
                }
                base.dataContext.SubmitChanges();
                hotNews = (from e in base.dataContext.HotNewsProducts
                           orderby e.NProOrder
                           select e).ToList<HotNewsProduct>();
                List<int> lstIDHotNews = new List<int>();
                foreach (HotNewsProduct hot in hotNews)
                {
                    lstIDHotNews.Add(hot.NProId);
                }
                newNews = (from n in base.dataContext.NewsProducts
                           where lstIDHotNews.Contains(n.NProId)
                           select new NewsProductResult
                           {
                               id = n.NProId,
                               title = n.NProTitle,
                               intro = n.NProIntro,
                               province = n.Province,
                               pubDate = n.NProDate,
                               price = n.NProPrice,
                               priceUnit = n.NProPriceUnit,
                               viewCount = n.NProViewCount,
                               needType = n.NProNeedType,
                               state = n.NProState,
                               member = n.Member,
                               thumbs = (from t in n.NewsProductThumbs
                                         where t.NProThumbIsMain == true
                                         select t).First<NewsProductThumb>()
                           }).ToList<NewsProductResult>();
                newOrderNews = new List<NewsProductResult>(newNews.Count);
                for (i = 0; i < lstIDHotNews.Count; i++)
                {
                    foreach (NewsProductResult news in newNews)
                    {
                        if (news.id == lstIDHotNews[i])
                        {
                            newOrderNews.Add(news);
                            break;
                        }
                    }
                }
                resultNews = newOrderNews;
                return this.CreateListNews(page, rowPerPage, resultNews);
            }
            newNewss = from n in base.dataContext.NewsProducts
                       where false
                       select new NewsProductResult
                       {
                           id = n.NProId,
                           title = n.NProTitle,
                           intro = n.NProIntro,
                           province = n.Province,
                           pubDate = n.NProDate,
                           price = n.NProPrice,
                           priceUnit = n.NProPriceUnit,
                           viewCount = n.NProViewCount,
                           needType = n.NProNeedType,
                           state = n.NProState,
                           member = n.Member,
                           thumbs = (from t in n.NewsProductThumbs
                                     where t.NProThumbIsMain == true
                                     select t).First<NewsProductThumb>()
                       };
            return this.CreateListNews(page, rowPerPage, newNewss);
        }

        private bool checkTwoDate(DateTime d1, DateTime d2)
        {
            return ((((d1.Year == d2.Year) && (d1.Day == d2.Day)) && (d1.Month == d2.Month)) && (d1.Hour == d2.Hour));
        }


        public FetchProductResult searchByProvince(int provinceId, int page, int rowPerPage)
        {
            IEnumerable<NewsProductResult> searchNews = null;

            searchNews = from n in this.dataContext.NewsProducts
                         orderby n.NProUpTime descending
                         where n.ProvId == provinceId
                         select new NewsProductResult
                         {
                             id = n.NProId,
                             title = n.NProTitle,
                             intro = n.NProIntro,
                             province = n.Province,
                             pubDate = n.NProDate,
                             price = n.NProPrice,
                             priceUnit = n.NProPriceUnit,
                             viewCount = n.NProViewCount,
                             needType = n.NProNeedType,
                             member = n.Member,
                             state = n.NProState,
                             thumbs = (from t in n.NewsProductThumbs
                                       where t.NProThumbIsMain == true
                                       select t).First()
                         };

            return CreateListNews(page, rowPerPage, searchNews);
        }

        public List<Member> getHotMember(FetchProductResult lstProduct)
        {
            List<Member> hotNews = null;

            hotNews = ((from n in lstProduct.products.AsQueryable()
                        orderby n.NProUpTime descending
                        select n.Member).Distinct()).ToList();
            return hotNews;
        }

        private FetchProductResult CreateListNews(int page, int rowPerPage, IEnumerable<NewsProductResult> newNews)
        {
            if (newNews != null)
            {
                List<NewsProductResult> pagedNewMemers = newNews.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();
                int totalPages = (int)Math.Ceiling((double)newNews.Count() / rowPerPage);
                List<NewsProduct> lstNews = new List<NewsProduct>(totalPages);
                NewsProduct news;
                foreach (var i in pagedNewMemers)
                {
                    news = new NewsProduct();
                    news.NProId = i.id;
                    news.NProTitle = i.title;
                    news.NProIntro = i.intro;
                    news.NProViewCount = i.viewCount;
                    news.NProDate = i.pubDate;
                    news.NProPrice = i.price;
                    news.NProPriceUnit = i.priceUnit;
                    news.Province = i.province;
                    news.NProNeedType = i.needType;
                    news.Member = i.member;
                    news.NProState = i.state;
                    news.NProLike = i.like;
                    if (i.thumbs != null)
                    {
                        news.NewsProductThumbs = new EntitySet<NewsProductThumb>();
                        NewsProductThumb thumb = new NewsProductThumb();
                        thumb.NProThumbName = i.thumbs.NProThumbName;
                        news.NewsProductThumbs.Add(thumb);
                    }
                    else
                    {
                        news.NewsProductThumbs = null;
                    }
                    //news.MemId = this.memberId;
                    lstNews.Add(news);
                }
                FetchProductResult result;
                result.totalPages = totalPages;
                result.products = lstNews;
                return result;
            }
            else
            {
                FetchProductResult result;
                result.totalPages = 0;
                result.products = null;
                return result;
            }
        }

        public List<Province> LoadAllProvince()
        {
            List<Province> provinces = (from p in this.dataContext.Provinces
                                        select p).ToList();
            return provinces;
        }

        public bool AddComment(string content, int newsId, int memberId, int? comIdReply)
        {
            NewsProduct news = getNews(newsId);
            if (news != null)
            {
                NewsProductComment comment = new NewsProductComment();
                comment.ComDate = DateTime.Now;
                comment.ComContent = content;
                comment.MemIdSender = memberId;
                if (comIdReply != null)
                {

                    comment.ComIdReply = comIdReply.Value;
                }
                news.NewsProductComments.Add(comment);
                Save();
                return true;
            }
            return false;
        }

        internal void Refresh(NewsProduct product)
        {
            this.dataContext.Refresh(RefreshMode.OverwriteCurrentValues, product);
        }

        /// <summary>
        /// Minh Thêm: lấy kết quả tìm kiếm
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rowPerPage"></param>
        /// <param name="cateId"></param>
        /// <returns></returns>
        public FetchProductResult AllNewsProductBySearch(int page, int rowPerPage, int? cateId, string inputText)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (cateId != null)
            {
                newNews = from n in this.dataContext.NewsProducts
                          where (n.CateId == cateId && n.NProTitle.Contains(inputText))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            else
            {
                newNews = from n in this.dataContext.NewsProducts
                          where (n.NProTitle.Contains(inputText))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            return CreateListNews(page, rowPerPage, newNews);
        }

        public List<NewsProduct> getProductByCategory(int catId)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where e.CateId == catId orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
            return result;
        }
        public List<Category> getSubCate(int catId)
        {

            List<Category> result = (from e in this.dataContext.Categories where e.ParentCategory.CateId == catId select e).ToList<Category>();
            return result;
        }
        public List<NewsProduct> getProductByMem(int memId)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where e.MemId == memId orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getProductByTitle(string title, string CatId)
        {

            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProTitle.Contains(title) && e.Category.PageId == int.Parse(CatId)) orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
            if (result.Count == 0)
            {
                List<Category> cat = new CategoryHelper().getCates(int.Parse(CatId));
                List<int?> catId = new List<int?>();

                for (int i = 0; i < cat.Count; i++)
                {
                    catId.Add(cat[i].CateId);

                }
                result = (from e in this.dataContext.NewsProducts where (e.NProTitle.Contains(title) && catId.Contains(e.Category.ParentCateId)) orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
            }
            return result;
        }

        public List<NewsProduct> getProductByType(string typeId)
        {

            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where e.NProNeedType.Equals(typeId) orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getProductByPrice(decimal? Price)
        {
            if (Price == null)
            {
                return null;
            }
            else
            {
                List<NewsProduct> result = (from e in this.dataContext.NewsProducts where e.NProPrice == Price orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_RELATIONSHIP).ToList<NewsProduct>();
                return result;
            }
        }

        public List<NewsProductComment> getListCommentByProductId(int pId)
        {
            List<NewsProductComment> result = (from e in this.dataContext.NewsProductComments where (e.NProId == pId && e.ComIdReply == null) orderby e.ComDate descending select e).ToList<NewsProductComment>();
            return result;
        }
        public List<NewsProductComment> getListCommentReplyByCommentId(int cId)
        {
            List<NewsProductComment> result = (from e in this.dataContext.NewsProductComments where e.ComIdReply == cId orderby e.ComDate descending select e).ToList<NewsProductComment>();
            return result;
        }

        public List<NewsProduct> getSixLatestNews(int pageID)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProState == true && e.Category.PageId == pageID) orderby e.NProDate descending select e).Take(5).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getFourLastestNewbyCategory(int catId)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProState == true && e.CateId == catId) orderby e.NProDate descending select e).Take(4).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getAllNewbyCategory(int catId)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProState == true && e.CateId == catId) orderby e.NProDate descending select e).ToList<NewsProduct>();
            return result;
        }
        public List<NewsProduct> getPopularNews()
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where e.NProNeedType.Contains("TD") orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_POPULAR).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getNewerNews(int proId)
        {
            NewsProduct cur = (from e in this.dataContext.NewsProducts where e.NProId == proId select e).SingleOrDefault();
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProDate >= cur.NProDate && e.CateId == cur.CateId) orderby e.NProDate descending select e).Take(Config.NUM_ITEMS_NEWER).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getOlderNews(int proId)
        {
            //
            NewsProduct cur = (from e in this.dataContext.NewsProducts where e.NProId == proId select e).SingleOrDefault();
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.NProDate <= cur.NProDate && e.CateId == cur.CateId) orderby e.NProDate descending select e).ToList<NewsProduct>();
            return result;
        }

        public List<NewsProduct> getNewestNewsByCate(int CateId)
        {
            List<NewsProduct> result = (from e in this.dataContext.NewsProducts where (e.CateId == CateId) orderby e.NProDate descending select e).Take(Config.ITEMS_PER_PAGE).ToList<NewsProduct>();
            return result;
        }

        public NewsProduct getNewsProductbyID(string proId)
        {
            NewsProduct result = (from e in this.dataContext.NewsProducts where (e.NProId == int.Parse(proId)) select e).SingleOrDefault();
            return result;
        }

        public FetchProductResult AllNewsBySearch(int page, int rowPerPage, int? cateId, string inputDate)
        {
            IEnumerable<NewsProductResult> newNews = null;
            string[] arr = inputDate.Split('/');
            // DateTime date =DateTime.ParseExact(inputDate,"dd/mm/yyyy",null);
            //  DateTime preDate = date.Add(new TimeSpan(-1,0,0,0));
            //DateTime nextDate = date.Add(new TimeSpan(1,0,0,0));
            if (cateId != null)
            {
                newNews = from n in this.dataContext.NewsProducts
                          //  where (n.CateId == cateId &&  n.NProDate>preDate && n.NProDate<nextDate)
                          where (n.CateId == cateId && n.NProDate.Year == int.Parse(arr[2]) && n.NProDate.Month == int.Parse(arr[1]) && n.NProDate.Day == int.Parse(arr[0]))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            else
            {
                newNews = from n in this.dataContext.NewsProducts
                          where (n.NProDate.Year == int.Parse(arr[2]) && n.NProDate.Month == int.Parse(arr[1]) && n.NProDate.Day == int.Parse(arr[0]))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            return CreateListNews(page, rowPerPage, newNews);
        }

        public bool SaveNewsProduct(NewsProduct pro, string memId)
        {
            if (pro.NProId.Equals("0"))
            {
                return true;
            }
            else
            {
                try
                {
                    NewsProduct tmp = getNewsProductbyID(pro.NProId + "");
                    tmp.NProLike = pro.NProLike;
                    Save();
                    MemberLikeNewsProduct mlike = new MemberLikeNewsProduct();
                    mlike.MemId = int.Parse(memId);
                    mlike.NProId = pro.NProId;
                    this.dataContext.MemberLikeNewsProducts.InsertOnSubmit(mlike);
                    this.dataContext.SubmitChanges();
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        public bool SaveMemberSaveNewsProduct(string memid, string newid)
        {
            try
            {
                MemberSaveNewsProduct news = new MemberSaveNewsProduct();
                news.MemberId = int.Parse(memid);
                news.NewsProductId = int.Parse(newid);
                this.dataContext.MemberSaveNewsProducts.InsertOnSubmit(news);
                this.dataContext.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public FetchProductResult AllNewsProductSaved(int page, int rowPerPage, int? cateId, List<int> lstId)
        {
            IEnumerable<NewsProductResult> newNews = null;
            if (cateId != null)
            {
                newNews = from n in this.dataContext.NewsProducts
                          //  where (n.CateId == cateId &&  n.NProDate>preDate && n.NProDate<nextDate)
                          where (n.CateId == cateId && lstId.Contains(n.NProId))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            else
            {
                newNews = from n in this.dataContext.NewsProducts
                          where (lstId.Contains(n.NProId))
                          orderby n.NProDate descending
                          select new NewsProductResult
                          {
                              id = n.NProId,
                              title = n.NProTitle,
                              intro = n.NProIntro,
                              province = n.Province,
                              pubDate = n.NProDate,
                              price = n.NProPrice,
                              priceUnit = n.NProPriceUnit,
                              viewCount = n.NProViewCount,
                              member = n.Member,
                              state = n.NProState,
                              thumbs = (from t in n.NewsProductThumbs
                                        where t.NProThumbIsMain == true
                                        select t).First()
                          };
            }
            return CreateListNews(page, rowPerPage, newNews);
        }

        public List<MemberSaveNewsProduct> getAllByMemId(int memid)
        {
            List<MemberSaveNewsProduct> result = (from e in this.dataContext.MemberSaveNewsProducts where e.MemberId == memid select e).ToList<MemberSaveNewsProduct>();
            return result;
        }

        public void changeNewsProductState(string id)
        {
            NewsProduct news = getNewsProductbyID(id);
            if (news.NProState == true)
                news.NProState = false;
            else
                news.NProState = true;
            this.dataContext.SubmitChanges();
        }


    }
}